package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @title: EmployeeController
 * @Author 椎名真白
 * @Date: 2022-04-25 15:05
 * @Version 1.0
 */

@Slf4j
@RestController
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * @description:
     * @author: 椎名真白
     * @date: 2022-04-25 15:09
     * @param: employee
     * @param: request
     * @return: com.itheima.reggie.common.R<com.itheima.reggie.pojo.Employee>
     **/
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        //获取用户名和密码
        String username = employee.getUsername();
        String password = employee.getPassword();

        //MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //获取mybatis的条件构造器 queryWrapper根据用户名查询用户信息
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        Employee emp = employeeService.getOne(queryWrapper);
        //判断用户名是否存在
        //卫语句风格（if判断）
        if (emp == null) {
            return R.error("用户名不存在");
        }
        //判断密码是否正确
        if (!emp.getPassword().equals(password)) {
            return R.error("密码输入错误");
        }
        //判断用户状态是否可用
        if (emp.getStatus() != 1) {
            return R.error("账号已经禁用");
        }
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //销毁session
    /*   session.removeAttribute()适用于清空指定的属性
        session.invalidate()是清除当前session的所有相关信息

        removeAttribute就是从session删除指定名称的绑定对象，也就是说调用此方法后再调用getAttribute(Stringname)时，不能获       取指定名称的绑定对象，但是session还存在。invalidate就是销毁此session对象，session对象中绑定的那些对象值也都不存在了   */
        //request.getSession().removeAttribute("employee");
        request.getSession().invalidate();
        return R.success("退出成功");

    }

    /**
     * @description: 新增用户信息
     * @author: 椎名真白
     * @date: 2022-04-26 10:41
     * @param: request
     * @param: employee
     * @return: com.itheima.reggie.common.R<java.lang.String>
     **/
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        employeeService.save(employee);
        return R.success("添加成功");
    }

    @GetMapping("page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        log.info("分页数据:{},{},{}",page,pageSize,name);
        //分页构造器
        Page pageInfo = new Page(page,pageSize);
        //条件构造器
        QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();

        queryWrapper.eq(StringUtils.isNotBlank(name),"name",name);

        queryWrapper.orderByDesc("update_time");

        employeeService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);

    }

    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
        //打印要修改的员工信息
        log.info("新增员工信息：{}", employee.toString());
        //获取当前登录用户的id
        Long id = (Long) request.getSession().getAttribute("employee");
        //修改员工修改事件信息
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(id);

        employeeService.updateById(employee);
        return R.success("修改员工状态信息成功");
    }

    /**
     * @description: 根据ID查询
     * @author: 椎名真白
     * @date: 2022-04-25 19:39
     * @param: id
     * @return: com.itheima.reggie.common.R<com.itheima.reggie.entity.Employee>
     **/
    @GetMapping("/{id}")
    public R<Employee> selectById(@PathVariable Long id){
        log.info("查找到的id:{}",id);
        Employee emp = employeeService.getById(id);
/*        //判断查找的用户信息是否存在
        if(emp==null){
            //不存在返回提示信息
            return R.error("查找的信息不存在");
        }else {
            //存在则将用户信息返回
            return R.success(emp);
        }*/
        return emp==null?R.error("查找的信息不存在"):R.success(emp);
    }
}
